const socketIo = require("socket.io");

socketIo.init = server => {
  const io = socketIo.listen(server);

  io.on("connection", socket => {
    socket.on("disconnect", () => {
      // 给其他用户广播
      socket.broadcast.emit("message", {
        username: "System",
        message: `${socket.username} 退出了聊天室`
      });
    });

    // 用户连接
    socket.on("setUsername", username => {
      socket.username = username;

      // 给其他用户广播
      socket.broadcast.emit("message", {
        username: "System",
        message: `${socket.username} 进入了聊天室`
      });
    });

    // 监听用户发来的消息
    socket.on("message", message => {
      // 给自己回消息
      socket.emit("message", {
        username: socket.username,
        message: message
      });

      // 给其他用户广播
      socket.broadcast.emit("message", {
        username: socket.username,
        message: message
      });
    });
  });
};

module.exports = socketIo;
